package com.quan.admin.listener;

import com.quan.admin.commons.constant.RabbitMQConstant;
import com.quan.admin.entity.SysMessage;
import com.quan.admin.entity.SysMessageToUser;
import com.quan.admin.service.SysMessageService;
import com.quan.admin.service.SysMessageToUserService;
import com.quan.commons.vo.MessageVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MQ监听-即时消息保存
 */
@RabbitListener(queues = RabbitMQConstant.SYSTEM_QUEUE_MESSAGE)
@Service
public class MessageListener {

    @Autowired
    private SysMessageService systemMessageService;

    @Autowired
    private SysMessageToUserService sysMessageToUserService;

    /**
     * 保存用户发送的即时消息
     * @param messageVo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(MessageVo messageVo, Channel channel, Message message) throws IOException {
        try {
            if(messageVo.getType().equals("topic")) {
                SysMessage msg = new SysMessage();
                msg.setType(1);
                msg.setStatus(1);
                msg.setTitle(messageVo.getTitle());
                msg.setContent(messageVo.getMessage());
                this.systemMessageService.save(msg);
            } else {
                SysMessage msg = new SysMessage();
                msg.setType(2);
                msg.setStatus(1);
                msg.setTitle(messageVo.getTitle());
                msg.setContent(messageVo.getMessage());
                this.systemMessageService.save(msg);

                List<SysMessageToUser> listToUser = new ArrayList<SysMessageToUser>();

                for (String s : messageVo.getTo()) {
                    SysMessageToUser toUserMsg = new SysMessageToUser();
                    toUserMsg.setUserId(Long.parseLong(s));
                    toUserMsg.setMessageId(msg.getId());
                    listToUser.add(toUserMsg);
                }
                this.sysMessageToUserService.saveBatch(listToUser);
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

}
